import django
from celery import Celery
from netmiko import ConnectHandler
from net_dev.middleware.dingding import send
import os
import re


# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'netmgmt.settings')
django.setup()

# 实力化
app = Celery('netmgmt')

# namespace='CELERY'作用是允许你在Django配置文件中对Celery进行配置
# 但所有Celery配置项必须以CELERY开头，防止冲突
app.config_from_object('django.conf:settings', namespace='CELERY')

# 自动从Django的已注册app中发现任务
app.autodiscover_tasks()




# @app.task
# def send_ding():
#
#     send("1.1.1.1 CPU爆满")



@app.task
def ap_check(ip):
    # host = {
    #     "device_type": "cisco_ios",
    #     "ip": ip,
    #     "username": "yunhui.adm",
    #     "password": "",
    # }
    # result = []
    # ssh = ConnectHandler(**host)
    # output = ssh.send_command("show ap dot11 5ghz load-info")
    # if os.path.exists("ap-info.txt"):
    #     os.remove("ap-info.txt")
    #     with open("ap-info.txt", "w") as f:
    #         f.write(output)
    # else:
    #     with open("ap-info.txt", "w") as f:
    #         f.write(output)
    # f = open("ap-info.txt", "r")
    # for i in f.readlines():
    #     if "CHNQDI" in i:
    #         if int(i.split()[3]) > 50 or int(i.split()[4]) > 50:
    #             result.append(f"<font size='4'>%s：当前利用率为：<b>%s</b>，客户端连接数为：<b>%s</b></font> <br>" % (
    #             i.split()[0], i.split()[3] + "%", i.split()[4]))

    host = {
        "device_type": "cisco_ios",
        "ip": ip,
        "username": "admin",
        "password": "admin@1234"
    }
    ssh = ConnectHandler(**host)
    output = ssh.send_command("show processes cpu | in CPU")
    output_list = re.findall("five seconds: (\d+)%/0%; one minute: (\d+)%; five minutes: (\d+)%", output)
    send("five seconds: %s; one minute: %s; five minutes: %s"%(output_list[0][0],output_list[0][1],output_list[0][2]))




from netaddr import IPNetwork,IPAddress
from ping3 import ping
import time
import nmap
from net_dev.models import Device

## 自动发现功能
@app.task

def discovers(ip, port):
    ## 对输入的参数进行判断，输入类型为两种：
    ## 一种：10.55.1.0-10.55.1.10   IP地址范围
    ## 二种：10.55.1.0/24  标准的掩码
    ## 通过长度去判断用户的参数属于那种类型
    if len(ip) > 15:
        ## 定义个空列表
        ip_list = []

        ## 10.55.1.0 - 10.55.1.10 用- 分隔 取数前端ip和后端iP
        start = ip.split("-")[0].strip()
        end = ip.split("-")[1].strip()

        ## 例如：10.55.1.0 - 10.55.1.10    start = 0   end = 10    循环1-10之间的数据
        for i in range(int(start.split(".")[3]), int(end.split(".")[3]) + 1):
            ip1 = start.split(".")[0] + "." + start.split(".")[1] + "." + start.split(".")[2] + "." + str(i)

            ## 进行ping判断
            result = ping(ip1)

            if result is None:
                pass
            else:
                ## 将ping通的地址加入到列表中
                ip_list.append(ip1)

        for list in ip_list:
            nm = nmap.PortScanner()

            ## 测试某个地址是否开通22端口
            result = nm.scan(list, arguments=f'-p {port}')
            #print("%s 设备22端口处于%s状态" % (list, result['scan'][list]['tcp'][port]['state']))
            Device.objects.create(ip=list,
                                  dev_name=list,
                                  weizhi="defalut",
                                  xinghao="default",
                                  diqu="default",
                                  jigui="default",
                                  username="admin",
                                  password="admin@123",
                                  vendor="other",
                                  leixing="other",
                                  enter="2",
                                  snmp="shopee123")

    else:

        ip1 = IPNetwork(ip)

        ## 获取子网掩码
        # print("子网掩码为：%s" % (ip1.netmask))
        ## 获取网络网络号
        # print("网络号为：%s" % (ip1.network))

        ## 获取网络号，并将网络号最后一位转换为字符串类型
        net = ip1.network
        net1 = str(net)
        ## 从字符串类型取出最后一位数据
        net2 = net1.split(".")[3]

        ## 获取广播地址，并将广播地址最后一位转换为字符串
        # print("广播地址为：%s" % (ip1.broadcast))

        ## 获取广播地址
        bro = ip1.broadcast
        ## 将广播地址转换为字符串
        bro1 = str(bro)

        ## 取出广播地址最后一位
        bro2 = bro1.split(".")[3]

        # print("包含主机数量：%s" % (ip1.size))
        # print("可用主机数量为：%s" % (ip1.size - 2))

        ## int(net2):是网络号的最后一位，代表IP地址的第一个网络号
        ## int(ip1.size)：ip1.size是包含主机数量，转换为字符串类型
        ## int(net2) + int(ip1.size)：网络号+主机数量 就是最后一个网络IP地址
        ip_list = []

        # #for 循环网络号和广播地址之间的数据；
        # #net2 代表网络号的最后一位，例如：10.55.1.0  net2=0  可用地址+1
        # #bor2 代表广播地址最后一位，例如：10.55.1.255 bro=255
        # #循环1 - 255 之间的数据；也就是1-254
        for i in range(int(net2) + 1, int(bro2)):

            ip2 = str(net1.split(".")[0]) + "." + str(net1.split(".")[1]) + "." + str(net1.split(".")[2]) + "." + str(i)
            result = ping(ip2)

            if result is None:
                pass
            else:
                ip_list.append(ip2)

        for list in ip_list:
            nm = nmap.PortScanner()

            ## 测试某个地址是否开通22端口
            result = nm.scan(list, arguments=f'-p {port}')
            # print("%s 设备22端口处于%s状态" % (list, result['scan'][list]['tcp'][port]['state']))
            Device.objects.create(ip=list,
                                  dev_name=list,
                                  weizhi="defalut",
                                  xinghao="default",
                                  diqu="default",
                                  jigui="default",
                                  username="admin",
                                  password="admin@123",
                                  vendor="other",
                                  leixing="other",
                                  enter="2",
                                  snmp="shopee123")



# import netmiko
#
# @app.task
# def cisco_ssh(ip,username,password):
#     sw = {
#         "device_type": "cisco_ios",
#         "ip": ip,
#         "username": username,
#         "password": password
#     }
#     conn = ' '
#     conn = netmiko.ConnectHandler(**sw)
#
#     return conn
#
#
#
# @app.task
# def hw_ssh(ip,username,password):
#     sw = {
#         "device_type": "huawei",
#         "ip": ip,
#         "username": username,
#         "password": password
#     }
#     conn = ' '
#     conn = netmiko.ConnectHandler(**sw)
#
#     return conn



from net_dev.models import monitor,Device
import datetime
@app.task
def snmp2_get(ip,community,oid):
    current_time = datetime.datetime.now()
    obj = Device.objects.all().values()
    for i in obj:
        if i["vendor"] == "cisco":
            data = os.system("snmpwalk -v 2c -c {} {} {}".format(i["snmp"], i["ip"], '1.3.6.1.4.1.9.2.1.57.0'))
            print(i["ip"] + "设备CPU利用率为%s"%(data))
        else:
            data = os.system("snmpwalk -v 2c -c {} {} {}".format(i["snmp"], i["ip"], '1.3.6.1.4.1.2011.6.3.4.1.4'))
            print(i["ip"] + "设备CPU利用率为%s" % (data))
    # monitor.objects.create(
    #     net_ip=ip,
    #     cpu_info=data,
    #     mem_info=data,
    #     temp=0,
    #     time=current_time,
    # )
    # print("cpu利用率为%s"%(data))



## 统计设备接口信息
from textfsm import TextFSM
import netmiko
from net_dev.models import inter,inter_count
@app.task
def ssh(ip):
    sw ={"device_type":"huawei","ip":ip,"username":"admin","password":"Admin@1234",}
    con = netmiko.ConnectHandler(**sw)
    output = con.send_command('dis inter bri')
    with open('/Users/yunhui.han/yunwei2/netmgmt/net_dev/static/textfsm/dis_inter_bri.textfsm') as f:
        fsm = TextFSM(f)
        result = fsm.ParseTextToDicts(output)
        for i in result:
            inter.objects.create(inters=i["INTERFACE"],
                                 state=i["PHY"],
                                 protocol=i["PROTOCOL"],
                                 inuti=i["INUTI"],
                                 oututi=i["OUTUTI"],
                                 inerros=i["INERRORS"],
                                 outerros=i["OUTERRORS"])

## 接口数量统计
@app.task
def inters_count(ip):
    sw = {"device_type": "huawei", "ip": ip, "username": "admin", "password": "Admin@1234", }
    con = netmiko.ConnectHandler(**sw)
    output = con.send_command('dis inter bri')

    count = []
    up = []
    down = []

    with open('/Users/yunhui.han/yunwei2/netmgmt/net_dev/static/textfsm/dis_inter_bri.textfsm') as f:
        time.sleep(1)
        fsm = TextFSM(f)
        result = fsm.ParseTextToDicts(output)
        for i in result:
            if "GigabitEthernet" in i["INTERFACE"]:
                count.append(i["INTERFACE"])
                if i["PHY"] == "up":
                    up.append(i["PHY"])
                else:
                    down.append(i["PHY"])
    inter_count.objects.create(ip=ip,inter_count=len(count),up=len(up),down=len(down))


